from database.db_handler import MysqlHander
from my_http import MyHttp
import urllib.request
from bs4 import BeautifulSoup
import glob
import jieba
import re
import json



class SZCode:
    def __init__(self):
        self.db = MysqlHander("config.ini")
        
    def gupiao_insert(self, code, name):
        trip_code = code.strip()
        #res = ',|;*'
        res = re.split('[<>]',name)
        trip_name = res[4]
        sql = "insert into entity_gupiao (Fcode, Fname, Fexchange_id, Fcreate_time, Fmodify_time) values "
        sql += "('" + trip_code + "','" + trip_name + "',2 , now(), now());"
        print(sql)
        insert = 0
        try:
            #pass
            self.db.execute_not_safe(sql)
            insert = 1
        except Exception as e:
            pass
        if 1 == insert:
            return
        update_sql = "update entity_gupiao set Fmodify_time=now(),Fexchange_id=2,Fname='" + trip_name + "' where Fcode='" + trip_code + "';"
        print(update_sql)
        try:
            #pass
            self.db.execute_not_safe(update_sql)
        except Exception as e:
            pass
        
    def get_http_data(self):
        for i in range (1, 131):
            #url = "http://www.szse.cn/api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=1747_zs&TABKEY=tab1&PAGENO=" + str(i) + "&ZSDM=399001&random=0.653174650818769"
            url = "http://www.szse.cn/api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=1110&TABKEY=tab1&PAGENO=" + str(i) + "&random=0.3368835461019912"
            json_http = MyHttp.http_json_data(url)
            json_data = json.loads(json_http)
            
            for sz_code in json_data[0]["data"]:
                self.gupiao_insert(sz_code["agdm"], sz_code["agjc"])

if __name__ == '__main__':
    code = SZCode()
    code.get_http_data()